// 权限 需要身份认证
const express = require("express")
const router = express.Router()
const mattersDB = require("../../db/matters")
const recordDB = require("../../db/record")

// 公益事项  ---- 添加
router.post("/matters/add", async (req, res) => {
  try {
    const { title, des, cover } = req.body
    if (!title.trim() || !des.trim() || !cover.trim()) {
      return res.send({
        code: 1,
        mes: "公益事项标题或内容格式不正确",
      })
    }
    // 查询是否存在
    const doc = await mattersDB.findOne({ title })
    if (doc)
      return res.send({
        code: 2,
        mes: "已存在该公益事项",
      })
    await mattersDB.create({ title, des, cover })

    res.send({
      code: 0,
      mes: "公益事项添加成功",
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

// 公益项目数据  ---- 添加
router.post("/record/add", async (req, res) => {
  try {
    const { title, des, num } = req.body
    // 校验
    if (!title.trim() || !des.trim() || !num.trim()) {
      return res.send({
        code: 2,
        mes: "公益活动格式有误",
      })
    }
    // 查看活动是否存在
    const doc = await recordDB.findOne({ title })
    if (doc)
      return res.send({
        code: 3,
        mes: "该活动已经存在",
      })
    await recordDB.create({ title, des, num })
    res.send({
      code: 0,
      mes: "活动数据添加成功",
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

module.exports = router
